package dxn.nl.file.center;

import dxn.nl.file.client.model.dto.TransferMessageDto;
import dxn.nl.file.client.model.enums.ExportDealResultTypeEnum;
import dxn.nl.file.client.model.enums.ExportMessageTypeEnum;
import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.SocketChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class SocketManager {
    private static final Logger logger = LoggerFactory.getLogger(SocketManager.class);
    public static String ipAddress = "";

    public static String getIp()
    {
        if(StringUtils.isNotBlank(ipAddress))
        {
            return ipAddress;
        }
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            ipAddress = inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("",e);
            ipAddress = "127.0.0.1"; // 默认本机IP
        }
        return ipAddress;
    }

    public static void sendNoResult(SocketChannel socketChannel, TransferMessageDto message)
    {
        try {
            ChannelFuture future = socketChannel.writeAndFlush(message);
//            if(future.isSuccess())
//            {
//                byteBuf.release();
//            }
        }
        catch (Exception ex)
        {
            logger.error("sendNoResult处理异常",ex);
        }
    }

    public static void sendErrorNoResult(SocketChannel socketChannel, TransferMessageDto message,String error)
    {
        sendErrorNoResult(socketChannel,message,ExportDealResultTypeEnum.fail.code,error);
    }

    public static void sendErrorNoResult(SocketChannel socketChannel, TransferMessageDto message,int dealResult,String error)
    {
        try {
            message.setType(ExportMessageTypeEnum.deal_result.code);
            message.getConfig().setErrorMessage(error);
            message.getConfig().setDealResult(dealResult);
            message.setData(null);
            sendNoResult(socketChannel,message);
        }
        catch (Exception ex)
        {
            logger.error("sendNoResult处理异常",ex);
        }
    }
}
